#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''


from pycommon import TBaseProtocol
import ClientFactory
import logging
import ClientParse
import time
import UserManager

CLIENT_STATE_INIT               = 0
CLIENT_STATE_AUTH               = 1
CLIENT_STATE_LOGINED            = 2
CLIENT_STATE_TO_CLOSE           = 3

class ClientSrv(TBaseProtocol.TBaseProtocol):

    def __init__(self, pid, addr):
        TBaseProtocol.TBaseProtocol.__init__(self)
        self.__id = pid
        self.__addr = addr
        self.__ip = addr.host.decode('utf-8')
        self.state = CLIENT_STATE_INIT
        self.toclosetime = time.time()
        self.uid = 0
        self.session = u''
        
    def getId(self):
        return self.__id

    def getIp(self):
        return self.__ip

    def getUid(self):
        return self.uid

    def getSession(self):
        return self.session

    def getState(self):
        return self.state

    def isLogined(self):
        return self.state == CLIENT_STATE_LOGINED
    
    def packetReceived(self, cmd, pkt):
        if self.state == CLIENT_STATE_TO_CLOSE:
            return
        try:
            ClientParse.parse(self, cmd, pkt)
        except Exception:
            logging.exception(u"Clientparse.parse(), cmd=%d" % cmd)
        
    def sendPacket(self, pkt):
        if not self.isConnected():
            logging.warn(u"sendPacket() not connected")
            return
        TBaseProtocol.TBaseProtocol.sendPacket(self, pkt)
    
    def connectionMade(self):
        logging.debug(u"ClientSrv.connectionMade() ip=%s", self.getIp()) 
        TBaseProtocol.TBaseProtocol.reset(self)
   
    def connectionLost(self, reason):
        logging.debug(u"ClientSrv.connectionLost %s", reason)
        self.state = CLIENT_STATE_TO_CLOSE
        ClientFactory.instance.removeProtocol(self)
    
    def onLoginRequest(self, uid, session):
        self.uid = uid
        self.session = session
        self.state = CLIENT_STATE_AUTH
        pass
    
    def isLogined(self):
        return self.uid != 0
    
    def onLogoutRequest(self):
        UserManager.instance.onUserLeave(self.uid, Const.USER_LEAVE_LOGOUT)
        self.goToClose()

    def onLoginSuc(self):
        logging.debug(u"onLoginSuc(), uid=%d",self.uid)
        self.state = CLIENT_STATE_LOGINED

    def goToClose(self):
        self.state = CLIENT_STATE_TO_CLOSE
        self.toclosetime = time.time()
    
    def kick(self):
        logging.debug(u"Client.kick()")
        self.goToClose()

if __name__ == "__main__":
    pass